using System;
using System.IO;
using Byond.Frontend.Messages;
using Mvvm;
using Utils.DialogManagement;
using Utils.Messaging;

namespace Byond.Frontend.ViewModels
{
	public class ModifiedDocumentViewModel : ViewModelBase
	{
		private readonly IDocumentManager _documentManager;
		private readonly IDialogManager _dialogManager;

		private readonly DocumentModel _documentModel;
		private readonly Action _selectedHandler;

		public ModifiedDocumentViewModel(DocumentModel documentModel, Action selectedHandler)
		{
			_documentModel = documentModel;
			_selectedHandler = selectedHandler;
			Name = Path.GetFileNameWithoutExtension(documentModel.FileName);
		}

		public event MessageEventHandler SendMessage;

		public string Name { get; private set; }

		public void ShowDocument()
		{
			SendMessage(new EditDocumentRequest(_documentModel.FileName));
			_selectedHandler();
		}

		public void CloseDocument()
		{
			var dialog = _dialogManager.CreateMessageDialog(
				"Save the changes ?", "Close Patch", DialogMode.YesNoCancel);
			dialog.Yes = () =>
				{
					_documentManager.Save(_documentModel);
					_selectedHandler();
				};
			dialog.No = () =>
				{
					_documentManager.Discard(_documentModel);
					_selectedHandler();
				};

			dialog.Show();
		}
	}
}